package com.dcyao.musicserve.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dcyao.musicserve.common.R;
import com.dcyao.musicserve.domain.Consumer;
import com.dcyao.musicserve.domain.dto.ConsumerDTO;
import com.dcyao.musicserve.mapper.ConsumerMapper;
import com.dcyao.musicserve.service.ConsumerService;
import com.dcyao.musicserve.utils.TokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.dcyao.musicserve.common.Constants.SALT;

@Service
public class ConsumerServicelmp extends ServiceImpl<ConsumerMapper, Consumer> implements ConsumerService {
    @Autowired
    private ConsumerMapper consumerMapper;

    @Override
    public R verityPasswd(ConsumerDTO adminRequest) {
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", adminRequest.getUsername());
        String secretPassword = DigestUtils.md5DigestAsHex((SALT + adminRequest.getPassword()).getBytes(StandardCharsets.UTF_8));
        queryWrapper.eq("password", secretPassword);
        Consumer one = getOne(queryWrapper);
        if (one != null) {
            BeanUtil.copyProperties(one, adminRequest, true);
            //设置token
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            adminRequest.setToken(token);
            return R.success("登录成功", adminRequest);
        } else {
            return R.error(400, "用户名或密码错误");
        }
    }

    @Override
    public R addUser(ConsumerDTO adminRequest) {
        if(isExist(adminRequest)) {
            return R.error(400, "用户已经被注册了");
        }
        // 开始注册用户 先将用户的所有的信息都复制下来
        Consumer consumer = new Consumer();
        BeanUtil.copyProperties( adminRequest, consumer);
        String secretPassword = DigestUtils.md5DigestAsHex((SALT + adminRequest.getPassword()).getBytes(StandardCharsets.UTF_8));
        consumer.setPassword(secretPassword);
        consumer.setAvatar("https://p9.itc.cn/q_70/images03/20230518/63b24f7da6234d33ac797fdd958e05eb.png");

        try{
            if(consumerMapper.insert(consumer) > 0) {
                return R.success("注册成功");
            }else {
                return R.error(400, "注册失败");
            }
        } catch (DuplicateKeyException exception) {
            return R.error(400, "注册失败");
        }
    }

    @Override
    public R findPage(Integer pageNum, Integer pageSize, String username) {
        LambdaQueryWrapper<Consumer> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(username)) {
            wrapper.like(Consumer::getUsername, username);
        }
        Page<Consumer> userPage = consumerMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return R.success("查询成功", userPage);
    }

    @Override
    public R updateUserMsg(ConsumerDTO updateRequest) {
        Consumer consumer = new Consumer();
        BeanUtils.copyProperties(updateRequest, consumer);
        //MD5加密
        String password = DigestUtils.md5DigestAsHex((SALT + updateRequest.getPassword()).getBytes(StandardCharsets.UTF_8));
        consumer.setPassword(password);
        if (consumerMapper.updateById(consumer) > 0) {
            return R.success("修改成功");
        } else {
            return R.error(400, "修改失败");
        }
    }

    @Override
    public R updatePassword(ConsumerDTO updatePasswordRequest) {
        if (!this.verityPasswd(updatePasswordRequest.getUsername(), updatePasswordRequest.getOldPassword())) {
            return R.error(400, "旧密码输入错误");
        }
        Consumer Consumer = new Consumer();
        Integer id = updatePasswordRequest.getId();
        Consumer.setId(id);
        String secretPassword = DigestUtils.md5DigestAsHex((SALT + updatePasswordRequest.getPassword()).getBytes(StandardCharsets.UTF_8));
        Consumer.setPassword(secretPassword);
        if (consumerMapper.updateById(Consumer) > 0) {
            return R.success("密码修改成功");
        } else {
            return R.error(400, "密码修改失败");
        }
    }

    @Override
    public boolean existUser(String username) {
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return consumerMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public boolean verityPasswd(String username, String password) {
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        String secretPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes(StandardCharsets.UTF_8));
        queryWrapper.eq("password", secretPassword);
        return consumerMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public R deleteUser(Integer id) {
        if (consumerMapper.deleteById(id) > 0) {
            return R.success("删除成功");
        } else {
            return R.error(400, "删除失败");
        }
    }

    @Override
    public R deleteBathIds(List<Integer> ids) {
        int i = consumerMapper.deleteBatchIds(ids);
        if (i < 0) {
            return R.error(400, "批量删除失败");
        }
        return R.success("批量删除成功");
    }

    @Override
    public R allUser() {
        List<Consumer> consumers = consumerMapper.selectList(null);
        return R.success(null, consumers);
    }

    @Override
    public R userOfId(Integer id) {
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return R.success(null, consumerMapper.selectList(queryWrapper));
    }

    @Override
    public long consumerCount() {
        long a = consumerMapper.selectCount(null);
        return a;
    }

    @Override
    public Page<ConsumerDTO> needConsumerType(Page<ConsumerDTO> page) {
        return null;
    }

    @Override
    public boolean isExist(ConsumerDTO adminRequest) {
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", adminRequest.getUsername());
        return consumerMapper.selectCount(queryWrapper) > 0;
    }
}
